/**
 * Notes: 定时任务服务层 - 处理设备订单过期和设备状态更新
 * Date: 2025-01-27
 */

const DeviceOrderService = require('./device_order_service.js');
const DeviceService = require('./device_service.js');
const DeviceStatusMonitor = require('./device_status_monitor.js');
const SimpleFaultHandler = require('./simple_fault_handler.js');
const timeUtil = require('../../framework/utils/time_util.js');

// 全局设备状态监控实例
let deviceStatusMonitor = null;
let simpleFaultHandler = null;

class SchedulerService {

	/**
	 * 初始化设备状态监控服务
	 */
	async initDeviceStatusMonitoring() {
		if (!deviceStatusMonitor) {
			console.log('初始化设备状态监控服务...');
			deviceStatusMonitor = new DeviceStatusMonitor();
			simpleFaultHandler = new SimpleFaultHandler();
			
			// 启动设备状态监控
			await deviceStatusMonitor.startMonitoring();
			console.log('设备状态监控服务已启动');
		}
	}

	/**
	 * 检查并处理过期订单和设备状态
	 * 这个方法应该被定时任务调用（建议每分钟执行一次）
	 */
	async processExpiredOrdersAndDevices() {
		console.log('开始处理过期订单和设备状态检查...');
		
		try {
			// 0. 确保设备状态监控服务已启动
			await this.initDeviceStatusMonitoring();

			// 1. 检查并处理过期订单
			const deviceOrderService = new DeviceOrderService();
			const orderResult = await deviceOrderService.checkExpiredOrders();
			console.log('过期订单处理结果:', orderResult);

			// 2. 批量更新设备状态（检查设备使用时间是否到期）
			const deviceService = new DeviceService();
			await deviceService.batchUpdateDeviceStatus();
			console.log('设备状态批量更新完成');

			// 3. 检查设备故障并处理
			if (deviceStatusMonitor && simpleFaultHandler) {
				const offlineDevices = deviceStatusMonitor.getOfflineDevices();
				for (const deviceId of offlineDevices) {
					await simpleFaultHandler.handleDeviceFault(deviceId, 'offline', '设备离线');
				}
				console.log(`处理了 ${offlineDevices.length} 个离线设备`);
			}

			return {
				success: true,
				message: '定时任务执行成功',
				processTime: timeUtil.time(),
				orderResult: orderResult
			};

		} catch (error) {
			console.error('定时任务执行失败:', error);
			return {
				success: false,
				message: '定时任务执行失败',
				error: error.message,
				processTime: timeUtil.time()
			};
		}
	}

	/**
	 * 检查设备连接状态
	 * 定期检查设备的MQTT连接状态和设备在线状态
	 */
	async checkDeviceConnections() {
		console.log('开始检查设备连接状态...');
		
		try {
			// 确保设备状态监控服务已启动
			await this.initDeviceStatusMonitoring();

			// 检查MQTT连接状态
			const deviceService = new DeviceService();
			const mqttStatus = deviceService.getMqttConnectionStatus();
			
			if (!mqttStatus.connected && !mqttStatus.connecting) {
				console.log('定时任务：检测到MQTT未连接，触发重连');
				await deviceService.initMqttConnection();
			}

			// 检查设备在线状态
			if (deviceStatusMonitor) {
				await deviceStatusMonitor.checkDeviceOnlineStatus();
				const statusSummary = deviceStatusMonitor.getDeviceStatusSummary();
				console.log('设备状态摘要:', statusSummary);
			}
			
			return {
				success: true,
				message: 'MQTT连接和设备状态检查完成',
				mqttStatus: mqttStatus,
				deviceStatus: deviceStatusMonitor ? deviceStatusMonitor.getDeviceStatusSummary() : null,
				checkTime: timeUtil.time()
			};
			
		} catch (error) {
			console.error('设备连接检查失败:', error);
			return {
				success: false,
				message: '设备连接检查失败',
				error: error.message,
				checkTime: timeUtil.time()
			};
		}
	}

	/**
	 * 清理过期的未支付订单
	 * 清理超过30分钟未支付的订单（包括设备订单和预约订单）
	 */
	async cleanupUnpaidOrders() {
		console.log('开始清理过期未支付订单...');
		
		try {
			const DeviceOrderModel = require('../model/device_order_model.js');
			const AppointmentModel = require('../model/appointment_model.js');
			const deviceOrderModel = new DeviceOrderModel();
			
			// 查询30分钟前创建的未支付设备订单
			const expireTime = timeUtil.time() - 30 * 60 * 1000; // 30分钟前（毫秒）
			const unpaidDeviceOrders = await DeviceOrderModel.getAll({
				status: DeviceOrderModel.STATUS.PENDING,
				createTime: { $lt: expireTime }
			});

			let cleanedDeviceCount = 0;
			for (let order of unpaidDeviceOrders) {
				// 将订单状态更新为已过期
				await deviceOrderModel.updateStatus(order._id, DeviceOrderModel.STATUS.EXPIRED);
				cleanedDeviceCount++;
			}
			
			// 查询过期的未支付预约订单（预约时间已过期或创建时间超过30分钟）
			const currentTime = timeUtil.time(); // 毫秒
			const unpaidAppointments = await AppointmentModel.getAll({
				status: AppointmentModel.STATUS.PENDING_PAY
			});

			let cleanedAppointmentCount = 0;
			for (let appointment of unpaidAppointments) {
				const isExpired = (appointment.createTime * 1000) < expireTime || 
				                (appointment.appointmentTime * 1000) < currentTime;
				
				if (isExpired) {
					// 将预约状态更新为已取消
					await AppointmentModel.edit({ _id: appointment._id }, {
						status: AppointmentModel.STATUS.CANCELLED,
						updateTime: timeUtil.time()
					});
					cleanedAppointmentCount++;
				}
			}

			const totalCleaned = cleanedDeviceCount + cleanedAppointmentCount;
			
			return {
				success: true,
				message: `清理了 ${totalCleaned} 个过期未支付订单（设备订单:${cleanedDeviceCount}，预约订单:${cleanedAppointmentCount}）`,
				cleanedDeviceCount: cleanedDeviceCount,
				cleanedAppointmentCount: cleanedAppointmentCount,
				cleanTime: timeUtil.time()
			};

		} catch (error) {
			console.error('清理过期订单失败:', error);
			return {
				success: false,
				message: '清理过期订单失败',
				error: error.message,
				cleanTime: timeUtil.time()
			};
		}
	}

}

module.exports = SchedulerService;